package com.example.musicplayer.fragment.MusicPlayPage;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.musicplayer.R;
import com.example.musicplayer.entity.Music;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.util.DbUtil;
import com.example.musicplayer.util.MusicNotification;
import com.example.musicplayer.util.MusicPopUpWindow;
import com.example.musicplayer.util.SingletonMediaPlayer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

import jp.wasabeef.glide.transformations.BlurTransformation;


public class SongFragment extends Fragment implements View.OnClickListener {
    private View view;
    private MusicPopUpWindow popWnd;
    private DbUtil mDbUtil; // 数据库工具类

    // 控件
    private TextView mMusicName, mArtistName, mMusicCurrentTime, mMusicTotalTime;
    private ImageView mSkipToNextMusic, mSkipToPreviousMusic, mStartOrPauseMusic, mMusicAlbum, mBackGroundImg, mPlayMode;
    private ImageView mShowMusicList;
    private SeekBar mMusicProgress;
    private ImageView mILike;

    // 音乐播放
    private MusicService.MusicBinder mMusicService;
    private Music mMusic;
    private MediaPlayer mMediaPlayer;

    // 新建线程更新进度条
    private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mMusicProgress.setProgress(mMediaPlayer.getCurrentPosition());
                        mMusicCurrentTime.setText(getFormatTime(mMediaPlayer.getCurrentPosition()));
                        if (mMusicService.isPlaying()) {
                            mStartOrPauseMusic.setImageResource(R.drawable.stop_play_music_button);
                        } else {
                            mStartOrPauseMusic.setImageResource(R.drawable.start_play_music_button);
                        }
                    }
                });
            } else {
                Log.i("==============", "界面更新出错");
            }
            mHandler.postDelayed(mRunnable, 16); // 人类视力极限为16ms
        }
    };

    // 与MusicService建立连接
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("================", "建立连接");
            mMusicService = (MusicService.MusicBinder) service;
            // 如果播放时退出界面，设置重新进入界面后界面控件的属性
            setMusicAttributes(); // 设置基本属性
            mMusicCurrentTime.setText(getFormatTime(mMediaPlayer.getCurrentPosition())); // 设置当前时间
            mMusicProgress.setProgress(mMediaPlayer.getCurrentPosition()); // 设置当前进度
            if (mMediaPlayer.isPlaying()) {
                mStartOrPauseMusic.setImageResource(R.drawable.stop_play_music_button);
            } else {
                mStartOrPauseMusic.setImageResource(R.drawable.start_play_music_button);
            }
            mRunnable.run(); // 启动界面更新线程
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 断开连接时将binder对象置空
            Log.i("===============", "断开连接");
            mMusicService = null;
        }
    };


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_music_play_page_song, container, false);
        initView();
        mDbUtil = new DbUtil();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Intent intent = new Intent(view.getContext(), MusicService.class);
        view.getContext().bindService(intent, connection, Context.BIND_AUTO_CREATE);
        mMediaPlayer = SingletonMediaPlayer.getMediaPlayer();
        // 设置歌曲准备好的响应事件
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (getActivity() != null) {
                    setMusicAttributes();
                }
            }
        });
        Log.i("================", "++++++++++onActivityCreated");
        // 设置进度条改变的响应事件
        mMusicProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mMediaPlayer.seekTo(progress);
                    mMusicCurrentTime.setText(getFormatTime(mMediaPlayer.getCurrentPosition()));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mMediaPlayer.pause();

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mMediaPlayer.start();
                mStartOrPauseMusic.setImageResource(R.drawable.stop_play_music_button);

            }
        });
    }


    private void initView() {
        mMusicName = view.findViewById(R.id.music_name);
        mArtistName = view.findViewById(R.id.artist_name);
        mSkipToPreviousMusic = view.findViewById(R.id.skip_to_previous_music);
        mSkipToNextMusic = view.findViewById(R.id.skip_to_next_music);
        mStartOrPauseMusic = view.findViewById(R.id.play_or_pause_music);
        mMusicAlbum = view.findViewById(R.id.music_album);
        mBackGroundImg = Objects.requireNonNull(getActivity()).findViewById(R.id.bg_img_view);
        mMusicProgress = view.findViewById(R.id.music_progress);
        mMusicCurrentTime = view.findViewById(R.id.music_current_time);
        mMusicTotalTime = view.findViewById(R.id.music_total_time);
        mPlayMode = view.findViewById(R.id.play_mode);
        mShowMusicList = view.findViewById(R.id.show_music_list);
        mILike = view.findViewById(R.id.i_like);
        mMusicName.setSelected(true);
        mArtistName.setSelected(true);
        mSkipToPreviousMusic.setOnClickListener(this);
        mSkipToNextMusic.setOnClickListener(this);
        mStartOrPauseMusic.setOnClickListener(this);
        mPlayMode.setOnClickListener(this);
        mShowMusicList.setOnClickListener(this);
        mILike.setOnClickListener(this);
    }

    // 设置播放模式图标
    private void setCurrentPlayMode() {
        String currentPlayMode = mMusicService.getCurrentPlayMode();
        switch (currentPlayMode) {
            case "LIST":
                mPlayMode.setImageResource(R.drawable.play_mode_list);
                break;
            case "SINGLE":
                mPlayMode.setImageResource(R.drawable.play_mode_single);
                break;
            case "RANDOM":
                mPlayMode.setImageResource(R.drawable.play_mode_random);
                break;
        }
    }

    private void setMusicAttributes() {
        // 获取当前音乐
        mMusic = mMusicService.getCurrentMusic();
        // 设置专辑图片
        mMusicAlbum.setImageBitmap(mMusic.getAlbumArt());
        // 背景高斯模糊
        gaussianBlur(mMusic.getAlbumArt());
        // 设置当前播放模式
        setCurrentPlayMode();
        // 获取当前音乐播放总时长
        mMusicTotalTime.setText(getFormatTime(mMediaPlayer.getDuration()));
        // 设置seekbar最大进度
        mMusicProgress.setMax(mMediaPlayer.getDuration());
        // 获取音乐名称
        mMusicName.setText(mMusic.getName());
        // 获取歌手名称
        mArtistName.setText(mMusic.getArtist());
        // 设置“我喜欢”按钮的颜色
        if (mDbUtil.isILike(getContext(), mMusic.getId())) {
            // 在“我喜欢”列表
            mILike.setColorFilter(Color.RED);
        } else {
            // 不在“我喜欢列表”
            mILike.setColorFilter(Color.WHITE);
        }
    }

    private void gaussianBlur(Bitmap bitmap) {
        //加载背景，
        Glide.with(Objects.requireNonNull(getActivity()))
                .load(bitmap)
                .dontAnimate()
                .error(R.drawable.no_music_rotate_img)
                // 设置高斯模糊
                .apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 13)))
                .into(mBackGroundImg);
    }

    private void sendNotificationBroadCast(String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        if (getContext() != null) {
            getContext().sendBroadcast(intent);
        } else {
            Log.i("===========", "广播发送失败");
        }

    }

    private String getFormatTime(int time) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss");
        return dateFormat.format(new Date(time));
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.skip_to_previous_music:
                sendNotificationBroadCast(MusicNotification.ACTION_PREVIOUS);
                mStartOrPauseMusic.setImageResource(R.drawable.stop_play_music_button);
                setMusicAttributes();
                break;
            case R.id.skip_to_next_music:
                sendNotificationBroadCast(MusicNotification.ACTION_NEXT);
                mStartOrPauseMusic.setImageResource(R.drawable.stop_play_music_button);
                setMusicAttributes();
                break;
            case R.id.play_or_pause_music:
                if (mMusicService.isPlaying()) {
                    sendNotificationBroadCast(MusicNotification.ACTION_START_OR_PAUSE);
                    mStartOrPauseMusic.setImageResource(R.drawable.stop_play_music_button);
                } else {
                    sendNotificationBroadCast(MusicNotification.ACTION_START_OR_PAUSE);
                    mStartOrPauseMusic.setImageResource(R.drawable.start_play_music_button);
                }
                break;
            case R.id.play_mode:
                mMusicService.changePlayMode();
                setCurrentPlayMode();
                break;
            case R.id.show_music_list:
                popWnd = new MusicPopUpWindow(view.getContext(), mMusicService);
                popWnd.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.i_like:
                if (getContext() != null) {
                    // 如果已经在我喜欢歌单中，则从我喜欢歌单中删除
                    if (mDbUtil.isILike(getContext(), mMusic.getId())) {
                        if (mDbUtil.deleteMusicFromMusicList(getContext(), mMusic.getId(), "我喜欢")) {
                            mILike.setColorFilter(Color.WHITE); // 图标设置为白色
                        } else {
                            return;
                        }
                    } else {
                        if (mDbUtil.addMusicToMusicList(getContext(), mMusic.getId(), "我喜欢")) {
                            mILike.setColorFilter(Color.RED);
                        } else {
                            return;
                        }
                    }
                } else {
                    Log.i("===============", "我喜欢图标设置出错");
                }
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(mRunnable);
        view.getContext().unbindService(connection);
    }

    @Override
    public void onStop() {
        super.onStop();
    }
}
